package com.medical.sys.service.impl;

import com.medical.sys.mapper.DepartmentMapper;
import com.medical.sys.model.Department;
import com.medical.sys.service.DepartmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2015-08-28.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    public Department selectByPrimaryKey(String id) {
        return departmentMapper.selectByPrimaryKey(id);
    }

    public List<Department> selectAllDepartment() {
        return departmentMapper.selectAll();
    }

    public void saveDepartment(Department department) {
        if(department!=null){
            if(StringUtils.isEmpty(department.getId())) {
                department.setId(UUID.randomUUID().toString());
            }
            if(StringUtils.isEmpty(department.getName())){
                throw new CustomizeException("name为空值");
            }
            if(StringUtils.isEmpty(department.getDescription())){
                throw new CustomizeException("description为空值");
            }
            if(StringUtils.isEmpty(department.getType())){
                throw new CustomizeException("type为空值");
            }
            List<Department> list=departmentMapper.selectAll();
            for(Department department1:list){
                if(department1.getName().equals(department.getName())){
                    throw new CustomizeException("已存在此名称");
                }
            }
            departmentMapper.insert(department);
        }else{
            throw new CustomizeException("对象为空");
        }
    }

    @Override
    public void updateByPrimaryKey(Department record) {
        departmentMapper.updateByPrimaryKey(record);
    }

    public void deleteDepartment(String id) {
        deleteDepartment(id, false);
    }

    public void deleteDepartment(String id, Boolean administrator) {

        if(administrator) {
            departmentMapper.deleteByPrimaryKey(id);
        }else{
            Department d = selectByPrimaryKey(id);
            d.setDeleted(true);
            departmentMapper.updateByPrimaryKey(d);
        }
    }


}
